package com.wyz.calibur.infrastructure.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Wei yz
 * @ClassName: JWTTokenUtil
 * @Description: 认证工具
 * @date 2022/1/23 14:30
 */
public class JWTTokenUtil {
    private static final Logger log = LoggerFactory.getLogger(JWTTokenUtil.class);


    /***
     * 过期时间 单位（秒）
     */
    private static int expiration = 30 * 60;
    /**
     * jwt key值
     */
    private static String key = "weiyaozhongshigedashuaige";
    /**
     * 载荷名1 用于map key值存放用户名
     */
    private static String sub = "wyz";

    /**
     * 创建token
     *
     * @return
     */
    public static String create(String username) {
        return JWTUtil.createToken(payload(username), key.getBytes());
    }

    /**
     * 刷新token过期时间
     *
     * @param token
     * @return
     */
    public static String refresh(String token) throws Exception {
        // 解析token 拿到username
        JWT jwt = JWTUtil.parseToken(token);
        if (ObjectUtil.isEmpty(jwt)) {
            throw new Exception("token解析失败");
        }
        String username = (String) jwt.getPayload(sub);
        if (StrUtil.isBlank(username)) {
            throw new Exception("token解析失败,载荷数据为空！");
        }
        // 重置时间
        return JWTUtil.createToken(payload(username), key.getBytes());
    }

    /**
     * 获得用户名
     *
     * @param token
     * @return
     */
    public static String getSub(String token) throws Exception {
        // 解析token 拿到username
        JWT jwt = JWTUtil.parseToken(token);
        if (ObjectUtil.isEmpty(jwt)) {
            throw new Exception("token解析失败");
        }
        String username = (String) jwt.getPayload(sub);
        if (StrUtil.isBlank(username)) {
            throw new Exception("token解析失败,载荷数据为空！");
        }
        return username;
    }


    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static boolean validate(String token) throws Exception {
        // 获得jwt对象
        JWT jwt = JWTUtil.parseToken(token);
        if (ObjectUtil.isEmpty(jwt)) {
            log.error("==> token 解析失败！");
            throw new Exception("token解析失败");
        }
        // 校验token合法性、过期时间
        if (jwt.setKey(key.getBytes()).verify() && jwt.validate(0)) {
            return true;
        }
        return false;
    }

    /**
     * 参数
     *
     * @return
     */
    private static Map<String, Object> payload(String username) {
        Date date = new Date();
        Map<String, Object> payload = new HashMap<String, Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, date);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, DateUtil.offsetSecond(new Date(), expiration));
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, date);
        //载荷
        payload.put(sub, username);
        return payload;
    }

}
